package com.bpf.base.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.bpf.base.bean.system.TSysUserForm;
import com.bpf.base.model.system.TSysUser;
import com.bpf.base.service.system.TSysUserService;
import com.bpf.base.util.Collections3;
import com.bpf.base.util.MapUtil;

/**
 * 登录验证
 * 
 */
@Service(value = "customUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {

	
	private final static Logger logger = LoggerFactory.getLogger(CustomUserDetailsService.class);

	/**
	 * 用户登陆时调用此方法验证.
	 * 
	 * @see org.springframework.security.core.userdetails.UserDetailsService#loadUserByUsername(java.lang.String)
	 */

	@Autowired
	private TSysUserService userService;

	@Transactional(readOnly = true)
	public UserDetails loadUserByUsername(String username) {
		TSysUserForm userForm=new TSysUserForm();
		userForm.setUsername(username);
		List<TSysUser> users= userService.getAllTSysUser(MapUtil.toMap(userForm));
		if(Collections3.isEmpty(users)){
			throw new UsernameNotFoundException("User not Found");
		}

		boolean enables = true;
		boolean accountNonExpired = true;
		boolean credentialsNonExpired = true;
		boolean accountNonLocked = true;

		Collection<GrantedAuthority> ga = new ArrayList<GrantedAuthority>();
		
		UserDetails userdetail = new org.springframework.security.core.userdetails.User(
				users.get(0).getUsername(), users.get(0).getPassword(), enables, accountNonExpired,
				credentialsNonExpired, accountNonLocked, ga);
	
		return userdetail;

	}
}
